package com.fat.spzx.manager.util;

import com.fat.spzx.model.entity.system.SysMenu;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

public class MenuTree {

    public static List<SysMenu> buildTree(List<SysMenu> sysMenuList) {
        ArrayList<SysMenu> treeList = new ArrayList<>();
        for (SysMenu sysMenu : sysMenuList) {
            if(sysMenu.getParentId() == 0) {
                treeList.add(findChildren(sysMenu,sysMenuList));
            }
        }
        return treeList;
    }

    private static SysMenu findChildren(SysMenu sysMenu, List<SysMenu> sysMenuList) {
        ArrayList<SysMenu> trees = new ArrayList<>();
        for (SysMenu menu : sysMenuList) {
            if (menu.getParentId() == sysMenu.getId()){
                trees.add(findChildren(menu,sysMenuList));
            }
        }
        if(!ObjectUtils.isEmpty(trees)) {
            sysMenu.setChildren(trees);
        }
        return sysMenu;
    }

}
